//... existing code ...

//+------------------------------------------------------------------+
//| 处理止盈平仓 - 保持原版逻辑                                        |
//+------------------------------------------------------------------+
void HandleTakeProfit()
{
    // 检查买入止盈
    if (buyTotalProfit >= g_StopProfit * buyOrderCount && buyTotalLots > 0)  
    {
        CloseAllPositions(1, "TP-B" + IntegerToString(buyBatchCounter));
    }

    // 检查卖出止盈
    if (sellTotalProfit >= g_StopProfit * sellOrderCount && sellTotalLots > 0)  
    {
        CloseAllPositions(-1, "TP-S" + IntegerToString(sellBatchCounter));
    }

    // 检查总盈利止盈
    double totalProfit = buyTotalProfit + sellTotalProfit;
    if (totalProfit >= CloseAll)
    {
        CloseAllPositions(0, "TP-ALL");
    }
}

//+------------------------------------------------------------------+
//| 处理止损平仓 - 保持原版逻辑                                        |
//+------------------------------------------------------------------+
void HandleStopLoss()
{
    // 检查买入止损
    if (buyTotalProfit <= StopLoss)
    {
        CloseAllPositions(1, "SL-B" + IntegerToString(buyBatchCounter));
    }

    // 检查卖出止损
    if (sellTotalProfit <= StopLoss)
    {
        CloseAllPositions(-1, "SL-S" + IntegerToString(sellBatchCounter));
    }
}

//+------------------------------------------------------------------+
//| 处理移动止盈 - 保持原版完整逻辑                                     |
//+------------------------------------------------------------------+
void HandleTrailingStop()
{
    // 临时存储当前批次信息
    MqlTick latest_price;
    if (!SymbolInfoTick(_Symbol, latest_price))
        return;

    double ask = latest_price.ask;
    double bid = latest_price.bid;

    // 获取动态止损价格
    double buyStopLoss = GetDynamicStopLoss(1, bid, stopLevel);
    double sellStopLoss = GetDynamicStopLoss(-1, ask, stopLevel);

    // 获取当前币种的最小获利点数
    double currentMinProfit = GetMinProfit();

    bool buyBatchModified = false;
    bool sellBatchModified = false;

    // 遍历所有持仓
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionSelectByTicket(PositionGetTicket(i)))
        {
            if (PositionGetString(POSITION_SYMBOL) == Symbol() &&
                PositionGetInteger(POSITION_MAGIC) == MagicNumber)
            {
                double posLots = PositionGetDouble(POSITION_VOLUME);
                double posPrice = PositionGetDouble(POSITION_PRICE_OPEN);
                double posProfit = PositionGetDouble(POSITION_PROFIT);
                double currentStopLoss = PositionGetDouble(POSITION_SL);

                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    // 检查是否需要修改止损
                    if ((buyStopLoss > currentStopLoss || currentStopLoss == 0) &&
                        buyStopLoss >= buyAveragePrice + currentMinProfit)
                    {
                        trade.PositionModify(PositionGetTicket(i), buyStopLoss, 0);
                        buyBatchModified = true;
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    // 检查是否需要修改止损
                    if ((sellStopLoss < currentStopLoss || currentStopLoss == 0) &&
                        sellStopLoss <= sellAveragePrice - currentMinProfit)
                    {
                        trade.PositionModify(PositionGetTicket(i), sellStopLoss, 0);
                        sellBatchModified = true;
                    }
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 获取动态止损价格 - 保持原版逻辑                                     |
//+------------------------------------------------------------------+
double GetDynamicStopLoss(int direction, double currentPrice, double stopLevelPoints)
{
    double stopPrice = 0;
    datetime currentTime = TimeCurrent();

    // direction: 1 为买入, -1 为卖出
    if (direction > 0) // 买入止损
    {
        // 搜索最近的低点作为止损
        for (int i = 1; i < MaxBars; i++)
        {
            double lowPrice = iLow(_Symbol, TF_Trailing, i);
            if (lowPrice == 0)
                continue;

            // 计算潜在的止损价格
            stopPrice = NormalizeDouble(lowPrice - delta * _Point, _Digits);

            // 买单的止损价要比当前价格低于基础止损点，挂单等价格回调后触发
            if(stopPrice < currentPrice-stopLevelPoints*_Point)
            {
                // 创建可视化标记
                CreateStopLossMarker("FIND Buy", iTime(_Symbol, TF_Trailing, i), stopPrice, 159, clrWhite);
                if(currentPrice>buyAveragePrice){ //当市场价开始大于当前价可以盈利时，绘制买单止盈的价格
                    CreateStopLossMarker("STOP Buy", currentTime + PeriodSeconds(), stopPrice, 6, clrRed);
                }

                // 创建最小止损距离标记
                if (stopLevelPoints > 0)
                {
                    CreateStopLossMarker("STOPLEVEL-",
                                         currentTime + PeriodSeconds(),
                                         currentPrice - stopLevelPoints,
                                         4,
                                         clrRed);
                }
                break;
            }
            stopPrice = 0;
        }
    }
    else if (direction < 0) // 卖出止损
    {
        // 搜索最近的高点作为止损
        for (int i = 1; i < MaxBars; i++)
        {
            double highPrice = iHigh(_Symbol, TF_Trailing, i);
            if (highPrice == 0)
                continue;

            // 计算潜在的止损价格
            stopPrice = NormalizeDouble(highPrice + delta * _Point, _Digits);

            // 检查是否满足最小止损距离要求 卖单止损价要高于当前价格+基础止损点，保证单据可以挂出去
            if (stopPrice>currentPrice + stopLevelPoints*_Point)
            {
                // 创建可视化标记
                CreateStopLossMarker("FIND Sell", iTime(_Symbol, TF_Trailing, i), stopPrice, 159, clrWhite);
                if(currentPrice<sellAveragePrice){
                    CreateStopLossMarker("STOP Sell", currentTime + PeriodSeconds(), stopPrice, 6, clrBlue);    
                }

                // 创建最小止损距离标记
                if (stopLevelPoints > 0)
                {
                    CreateStopLossMarker("STOPLEVEL+",
                                         currentTime + PeriodSeconds(),
                                         currentPrice + stopLevelPoints,
                                         4,
                                         clrBlue);
                }
                break;
            }
            stopPrice = 0;
        }
    }

    return stopPrice;
}

//+------------------------------------------------------------------+
//| 创建止损标记 - 保持原版逻辑                                        |
//+------------------------------------------------------------------+
void CreateStopLossMarker(string name, datetime time, double price, int arrowCode, color clr)
{
    ObjectDelete(0, name);
    ObjectCreate(0, name, OBJ_ARROW, 0, time, price);
    ObjectSetInteger(0, name, OBJPROP_ARROWCODE, arrowCode);
    ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
}

//+------------------------------------------------------------------+
//| 开仓和加仓逻辑 - 保持原版完整逻辑(关键部分)                         |
//+------------------------------------------------------------------+
void OpenOrAddPosition()
{
    MqlTick latest_price;
    if (!SymbolInfoTick(_Symbol, latest_price))
        return;

    double ask = latest_price.ask;
    double bid = latest_price.bid;
    double newOrderLots;
    double newOrderPrice;

    // 买入逻辑 - 保持原版完整逻辑
    if (Buy && buyPendingOrders == 0 && buyOrderCount < g_MaxOrderCount && IsPriceBelowMA())
    {
        double atr = g_atr;
        double multiplier = g_MultiplierOnLoss;
        if(buyOrderCount < 5) {
            newOrderLots = NormalizeDouble(MathPow(g_MultiplierOnLoss, buyOrderCount) * g_InitialLot, 2);
        } else {
            multiplier = CalculateSmartLotMultiplier(true, lowestBuyPrice, ask, atr);  // 智能马丁
            newOrderLots = NormalizeDouble(lastBuyLot * multiplier, 2);
        }
        newOrderPrice = (buyOrderCount == 0) ? CalculateAddOrderPrice(ask, 0, ORDER_TYPE_BUY_STOP) : NormalizeDouble(lowestBuyPrice - g_AtrRange * atr, _Digits);
        bool canAdd = (buyOrderCount < SmartAddStart-1)
            ? IsValidOrderPrice(newOrderPrice, ask, ORDER_TYPE_BUY_STOP)
            : CanAddSmartOrder(true, buyOrderCount, lowestBuyPrice);
        if(canAdd && newOrderLots < AccountInfoDouble(ACCOUNT_MARGIN_FREE) / SymbolInfoDouble(_Symbol, SYMBOL_MARGIN_INITIAL))
        {
            MqlDateTime timeStruct; TimeToStruct(TimeCurrent(), timeStruct);
            if (!sj || (sj && timeStruct.hour > star && timeStruct.hour < end))
            {
                if (trade.BuyStop(newOrderLots, newOrderPrice, _Symbol, 0, 0, ORDER_TIME_GTC, 0, "Martingale EA"))
                {
                    lastBuyLot = newOrderLots;
                    PrintFormat("买入挂单 #%d 创建成功, 手数: %.2f, 价格: %.5f", OrderGetTicket(OrdersTotal() - 1), newOrderLots, newOrderPrice);
                    lastAddBarIndex = Bars(_Symbol, PERIOD_CURRENT);
                }
            }
        }
    }

    // 卖出逻辑 - 保持原版完整逻辑
    if (Sell && sellPendingOrders == 0 && sellOrderCount < g_MaxOrderCount && IsPriceAboveMA())
    {
        double atr = g_atr;
        double multiplier = g_MultiplierOnLoss;
        if(sellOrderCount < 5) {
            newOrderLots = NormalizeDouble(MathPow(g_MultiplierOnLoss, sellOrderCount) * g_InitialLot, 2);
        } else {
            multiplier = CalculateSmartLotMultiplier(false, highestSellPrice, bid, atr);  // 智能马丁
            newOrderLots = NormalizeDouble(lastSellLot * multiplier, 2);
        }
        newOrderPrice = (sellOrderCount == 0) ? CalculateAddOrderPrice(bid, 0, ORDER_TYPE_SELL_STOP) : NormalizeDouble(highestSellPrice + g_AtrRange * atr, _Digits);
        bool canAdd = (sellOrderCount < SmartAddStart-1)
            ? IsValidOrderPrice(newOrderPrice, bid, ORDER_TYPE_SELL_STOP)
            : CanAddSmartOrder(false, sellOrderCount, highestSellPrice);
        if(canAdd && newOrderLots < AccountInfoDouble(ACCOUNT_MARGIN_FREE) / SymbolInfoDouble(_Symbol, SYMBOL_MARGIN_INITIAL))
        {
            MqlDateTime timeStruct; TimeToStruct(TimeCurrent(), timeStruct);
            if (!sj || (sj && timeStruct.hour > star && timeStruct.hour < end))
            {
                if (trade.SellStop(newOrderLots, newOrderPrice, _Symbol, 0, 0, ORDER_TIME_GTC, 0, "Martingale EA"))
                {
                    lastSellLot = newOrderLots;
                    PrintFormat("卖出挂单 #%d 创建成功, 手数: %.2f, 价格: %.5f", OrderGetTicket(OrdersTotal() - 1), newOrderLots, newOrderPrice);
                    lastAddBarIndex = Bars(_Symbol, PERIOD_CURRENT);
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 修改挂单 - 保持原版逻辑                                            |
//+------------------------------------------------------------------+
void ModifyOrders()
{
    MqlTick latest_price;
    if (!SymbolInfoTick(_Symbol, latest_price))
        return;

    double ask = latest_price.ask;
    double bid = latest_price.bid;
    
    // 获取挂单距离
    double orderDistance = GetOrderDistance();
    // 设置移动步长为挂单距离的三分之一
    double stepTrallOrders = orderDistance / 3.0;

    // 修改买入挂单
    if (buyStopTicket != 0 && OrderSelect(buyStopTicket))
    {
        double buyOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN);
        double newOrderPrice = NormalizeDouble(buyOpenPrice - stepTrallOrders, _Digits);

        // 只有当新价格与当前市场价格保持足够距离时才修改
        if (newOrderPrice - ask >= orderDistance)
        {
            if (!trade.OrderModify(buyStopTicket, newOrderPrice, 0, 0, 0, clrWhite))
            {
                // Print("Error ", GetLastError(), "   Order Modify Buy   OOP ", buyOpenPrice, "->", newOrderPrice);
            }
        }
    }

    // 修改卖出挂单
    if (sellStopTicket != 0 && OrderSelect(sellStopTicket))
    {
        double sellOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN);
        double newOrderPrice = NormalizeDouble(sellOpenPrice + stepTrallOrders, _Digits);

        // 只有当新价格与当前市场价格保持足够距离时才修改
        if (bid - newOrderPrice >= orderDistance)
        {
            if (!trade.OrderModify(sellStopTicket, newOrderPrice, 0, 0, 0, clrWhite))
            {
                // Print("Error ", GetLastError(), "   Order Modify Sell   OOP ", sellOpenPrice, "->", newOrderPrice);
            }
        }
    }
}